package com.nd.qa.shareplate.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.DeflateDecompressingEntity;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import com.nd.qa.shareplate.model.Role;
import com.nd.qa.shareplate.model.Session;

@Component
public class CSTools {
    private int expires = 3600;

    // dev环境
    private String serviceId = "7bee0827-1184-453e-af2b-87c7e5563b52";

    private String url = "http://betacs.101.com/v0.1";

    private String name = "dev_content_script";


    public String getAdminSession(String uid, String path, String Authorization) {
        Session session = getSession(uid, path, Role.ADMIN, Authorization);
        return session.getSession();
    }

    public String uploadPackage(String name, String localPath,String path) {
        String filepath = localPath;
        String host = "betacs.101.com";
        CSTools cs = new CSTools();
        UCTools uc = new UCTools();
        String Authorization = uc.get_bearer_token();
        String session = cs.getAdminSession("329000", path, Authorization);
        String url = "http://betacs.101.com/v0.1/upload?session=" + session;
        String urlStr = url;
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("path", "/" + "dev_content_script" + path);
        textMap.put("name", name);
        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("userfile", filepath);
        String res = fileUpload(urlStr, host, textMap, fileMap, "application/vnd.android.package-archiveasc");
        return res;
    }

    public String uploadScript(String name, String localPath,String path) {
        String filepath = localPath;
        String host = "betacs.101.com";
        CSTools cs = new CSTools();
        UCTools uc = new UCTools();
        String Authorization = uc.get_bearer_token();
        String session = cs.getAdminSession("329000", path, Authorization);
        String url = "http://betacs.101.com/v0.1/upload?session=" + session;
        String urlStr = url;
        Map<String, String> textMap = new HashMap<String, String>();
        textMap.put("path", "/" + "dev_content_script" + path);
        textMap.put("name", name);
        Map<String, String> fileMap = new HashMap<String, String>();
        fileMap.put("userfile", filepath);
        String res = fileUpload(urlStr, host, textMap, fileMap, "application/zip");
        return res;
    }
    
    public void downloadScript(String dentryId, String localPath,String path) {
        CSTools cs = new CSTools();
        UCTools uc = new UCTools();
        String Authorization = uc.get_bearer_token();
        String session = cs.getAdminSession("329000", path, Authorization);
        String url = "http://betacs.101.com/v0.1/download?dentryId=" + dentryId
        +"&session=" + session;
        String urlStr = url;
        cs.fileDownload(urlStr,localPath);
    }
    
    

    /**
     * 从内容服务获取session
     *
     * @param uid  用户UID
     * @param path 授权的目录
     * @param role 用户角色
     * @return JSONObject SESSION信息
     */
    private Session getSession(String uid, String path, Role role, String Authorization) {
        String result = "";
        Session session = new Session();
        Map<String, Object> requestBody = new HashMap<String, Object>();
        requestBody.put("path", "/" + this.name + path);
        requestBody.put("service_id", this.serviceId);
        requestBody.put("uid", uid);
        requestBody.put("role", role.getName());
        requestBody.put("expires", this.expires);

        try {
            // 创建连接
            URL url = new URL(this.url + "/sessions");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("POST");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Authorization", Authorization);
            connection.connect();

            // POST请求
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            JSONObject obj = JSONObject.fromObject(requestBody);
            out.writeBytes(obj.toString());
            out.flush();
            out.close();
            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String lines;
            // StringBuffer sb = new StringBuffer("");
            while ((lines = reader.readLine()) != null) {
                lines = new String(lines.getBytes(), "utf-8");
                // result.append(lines);
                result += lines;
            }
            System.out.println("获取session接口返回信息：" + result);
            reader.close();
            // 断开连接
            System.out.println("断开session连接");
            connection.disconnect();
            // 拼装数据
            JSONObject resultJsonObject = JSONObject.fromObject(result);
            session.setExpireAt(resultJsonObject.getLong("expire_at"));
            session.setPath(resultJsonObject.getString("path"));
            session.setRole(resultJsonObject.getString("role"));
            session.setServiceId(resultJsonObject.getString("service_id"));
            session.setSession(resultJsonObject.getString("session"));
            session.setUid(resultJsonObject.getInt("uid"));
            System.out.println("session拼装完成");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("返回session");
        return session;
    }

    /** 
     * @param args 
     * @throws IOException 
     */
    public static void main(String[] args)  {
//        String filepath = "http://192.168.239.106:8090/shareplate/resources/file/script-build/421490/sport.zip";
//        String host = "betacs.101.com";
//        CSTools cs = new CSTools();
//        UCTools uc = new UCTools();
//        String Authorization = uc.get_bearer_token();
//        String session = cs.getAdminSession("329000", "/Apk", Authorization);
//        String url = "http://betacs.101.com/v0.1/upload?session=" + session;
//        String urlStr = url;
//        Map<String, String> textMap = new HashMap<String, String>();
//        textMap.put("path", "/" + "dev_content_script" + "/Apk");
//        textMap.put("name", "abc.zip");
//        Map<String, String> fileMap = new HashMap<String, String>();
//        fileMap.put("userfile", filepath);
//        String res = fileUpload(urlStr, host, textMap, fileMap, "application/zip");
//        System.out.println("RES===" + res);

        CSTools cs = new CSTools();
        UCTools uc = new UCTools();
        String Authorization = uc.get_bearer_token();
        String session = cs.getAdminSession("329000", "/Apk", Authorization);
        String url = "http://betacs.101.com/v0.1/download?dentryId=" + "3890441d-31f2-4d53-ab77-c8fbf9a78878"
        +"&session=" + session;
        String urlStr = url;
        cs.fileDownload(urlStr,"D:\\CICODE\\abc.zip");

    }

    /** 
     * 上传文件
     * @param url 
     * @param host
     * @param textMap 
     * @param fileMap 
     * @param mimeType
     * @return 
     */
    public static String fileUpload(String urlStr, String host, Map<String, String> textMap,
            Map<String, String> fileMap, String mimeType) {
        String res = "";
        HttpClient httpclient = new DefaultHttpClient();

        // HttpHost proxy = new HttpHost(p.getHost(), Integer.valueOf(p.getPort()), "http");
        // httpclient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        // 请求路径
        HttpPost post = new HttpPost(urlStr);
        // 添加header头信息
        post.setHeader("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;)");
        // 注 这里一定不能添加 content-Type:multipart/form-data 属性 因为这里面有个boundary参数属性是不可控的。这个值是由浏览器生成的。如果强行指明和可能
        // 导致边界值不一致 就会请求失败
        // post.setHeader("content-Type", "multipart/form-data");
        post.setHeader("Host", host);
        post.setHeader("Accept-Encoding", "gzip");
        post.setHeader("charset", "utf-8");
        FileBody fileBody = new FileBody(new File(fileMap.get("userfile").toString()), mimeType, "utf-8");
        MultipartEntity entity = new MultipartEntity();
        // 添加消息体信息
        try {
            entity.addPart("name", new StringBody(textMap.get("name").toString(), Charset.forName("utf-8")));
            entity.addPart("path", new StringBody(textMap.get("path").toString(), Charset.forName("utf-8")));
            entity.addPart("imagefile", fileBody);
            post.setEntity(entity);

            HttpResponse response = httpclient.execute(post);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity entitys = response.getEntity();
                byte[] resByte = {};
                if (entitys != null) {
                    if (entitys.getContentEncoding() != null) {
                        if ("gzip".equalsIgnoreCase(entitys.getContentEncoding().getValue())) {
                            entitys = new GzipDecompressingEntity(entitys);
                        }
                        else if ("deflate".equalsIgnoreCase(entitys.getContentEncoding().getValue())) {
                            entitys = new DeflateDecompressingEntity(entitys);
                        }
                    }
                    resByte = EntityUtils.toByteArray(entitys);
                    JSONObject resultJsonObject = JSONObject.fromObject(new String(resByte, "utf-8"));
                    res = resultJsonObject.getString("dentry_id");
                    System.out.println("dentry_id:" + res);
                }
            }
            post.abort();
            httpclient.getConnectionManager().shutdown();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return res;
    }
    
    
    /**
    *
    */
    public  void fileDownload(String urlStr, String fileName) {
      
        FileOutputStream fos = null;  
        BufferedInputStream bis = null;  
        HttpURLConnection httpUrl = null;  
        URL url = null;  
        byte[] buf = new byte[8096];  
        int size = 0;  
  
        //建立链接  
        try {
            url = new URL(urlStr);
            httpUrl = (HttpURLConnection) url.openConnection();  
            //连接指定的资源  
            httpUrl.connect();  
            //获取网络输入流  
            bis = new BufferedInputStream(httpUrl.getInputStream());  
            //建立文件  
            File file = new File(fileName);  
            if(!file.exists()) {  
                if(!file.getParentFile().exists()) {  
                    file.getParentFile().mkdirs();  
                }  
                file.createNewFile();  
            }  
            fos = new FileOutputStream(fileName);  
      
            System.out.println("正在获取链接[" + urlStr + "]的内容...\n将其保存为文件["  
                        + fileName + "]");  
      
            //保存文件  
            while ((size = bis.read(buf)) != -1)  
                fos.write(buf, 0, size);  
      
            fos.close();  
            bis.close();  
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
        
        httpUrl.disconnect();  
        
   }
    

}
